import {Image, StyleSheet, View, Text, TouchableOpacity, useWindowDimensions, Animated, FlatList} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import {useEffect, useState} from "react";
import {SceneMap, TabView} from "react-native-tab-view";
import * as React from "react";
import OrderList from "@/components/OrderList/index";
import ProFlatList from "@/components/ProFlatList";
import { getOrderListByRequest } from "@/services/orederServices"
import { setOrderDetailByItem } from "@/store/slices/activityDetailSlice"
import {useDispatch} from "react-redux";

const AllRouter = function () {
    //0 待支付
    //1 已支付
    //2 已取消
    //3 已退款

    const [data, setData] = useState<any>([]);
    const [pages, setPages] = useState<any>(1);
    const [loading, setLoading] = useState<any>(false);
    const [current, setCurrent] = useState(1);

    const loadMoreData = function ({ intRefreshing, pages: tmpPages }) {

        if (tmpPages == 1) {
            return getOrderList(intRefreshing);
        };

        if (current > pages) {
            return intRefreshing && intRefreshing();
        };

        const baseData = {
            current: tmpPages,
            size: 10,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                const newData = res.data.items;
                setPages(res.data.pages)
                setData((prevData) => [...prevData, ...newData]);
                setCurrent(current + 1);
                intRefreshing && intRefreshing();
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    useEffect(() => {
        getOrderList();
    }, [])

    const getOrderList = function (intRefreshing?: any) {
        const baseData = {
            current: 1,
            size: 10,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                setPages(res.data.pages)
                setData(res.data.items)
                intRefreshing && intRefreshing();
            })
            .catch((err) => {
                console.log('err', err)
                intRefreshing && intRefreshing();
            })
    };

    // const requestData = function ({ pages, intRefreshing }) {
    //     if (pages == 1) {
    //         setTimeout(() => {
    //             const newData = tempData;
    //             setData(newData);
    //             setPages(pages);
    //             intRefreshing && intRefreshing();
    //         }, 1000);
    //     } else {
    //         setTimeout(() => {
    //             const newData = tempData;
    //             setData((prevData) => [...prevData, ...newData]);
    //             setPages((prevPage) => prevPage + 1);
    //             intRefreshing && intRefreshing();
    //         }, 1000);
    //     };
    // };

    return (
        <View style={{ height: "100%"}}>
           {/*<FlatList*/}
           {/*    data={data}*/}
           {/*    renderItem={(item) => <OrderList data={item} /> }*/}
           {/*/>*/}

            <ProFlatList
                data={data}
                renderItem={(item, index) => <OrderList data={item} key={`${index}AllRouter`} /> }
                pages={pages}
                requestData={loadMoreData}
                loading={loading}
                setLoading={setLoading}
            />
        </View>
    )
};


const UnpaidRouter = function () {
    //0 待支付
    //1 已支付
    //2 已取消
    //3 已退款

    const [data, setData] = useState<any>([]);
    const [pages, setPages] = useState<any>(1);
    const [loading, setLoading] = useState<any>(false);
    const [current, setCurrent] = useState(1);


    const loadMoreData = function ({ intRefreshing, pages: tmpPages }) {

        if (tmpPages == 1) {
            return getOrderList(intRefreshing);
        };

        console.log('pagesCounts', pages);

        if (current > pages) {
            return intRefreshing && intRefreshing();
        };

        const baseData = {
            current: tmpPages,
            size: 10,
            payStatus: 0,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                const newData = res.data.items;
                setPages(res.data.pages)
                setData((prevData) => [...prevData, ...newData]);
                setCurrent(current + 1);
                intRefreshing && intRefreshing();
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    useEffect(() => {
        getOrderList();
    }, [])

    const getOrderList = function (intRefreshing?: any) {
        const baseData = {
            current: 1,
            size: 10,
            payStatus: 0,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                console.log('res', res.data.items)
                setPages(res.data.pages)
                setData(res.data.items)
                intRefreshing && intRefreshing();
            })
            .catch((err) => {
                intRefreshing && intRefreshing();
            })
    };

    return (
        <View style={{ height: "100%"}}>
            {/*<FlatList*/}
            {/*    data={data}*/}
            {/*    renderItem={(item) => <OrderList data={item} /> }*/}
            {/*/>*/}

            <ProFlatList
                data={data}
                renderItem={(item, index) => <OrderList data={item} key={`${index}AllRouter`} /> }
                pages={pages}
                requestData={loadMoreData}
                loading={loading}
                setLoading={setLoading}
            />
        </View>
    )
};


const PaidRouter = function () {
    //0 待支付
    //1 已支付
    //2 已取消
    //3 已退款

    const [data, setData] = useState<any>([]);
    const [pages, setPages] = useState<any>(1);
    const [loading, setLoading] = useState<any>(false);
    const [current, setCurrent] = useState(1);


    const loadMoreData = function ({ intRefreshing, pages: tmpPages }) {

        if (tmpPages == 1) {
            return getOrderList(intRefreshing);
        };


        if (current > pages) {
            return intRefreshing && intRefreshing();
        };

        const baseData = {
            current: tmpPages,
            size: 10,
            payStatus: 1,
        };


        getOrderListByRequest(baseData)
            .then((res) => {
                const newData = res.data.items;
                setPages(res.data.pages)
                setData((prevData) => [...prevData, ...newData]);
                setCurrent(current + 1);
                intRefreshing && intRefreshing();
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    useEffect(() => {
        getOrderList();
    }, [])

    const getOrderList = function (intRefreshing?: any) {
        const baseData = {
            current: 1,
            size: 10,
            payStatus: 1,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                setPages(res.data.pages)
                setData(res.data.items)
                intRefreshing && intRefreshing();
            })
            .catch((err) => {
                intRefreshing && intRefreshing();
            })
    };

    return (
        <View style={{ height: "100%"}}>
            {/*<FlatList*/}
            {/*    data={data}*/}
            {/*    renderItem={(item) => <OrderList data={item} /> }*/}
            {/*/>*/}

            <ProFlatList
                data={data}
                renderItem={(item, index) => <OrderList data={item} key={`${index}AllRouter`} /> }
                pages={pages}
                requestData={loadMoreData}
                loading={loading}
                setLoading={setLoading}
            />
        </View>
    )
};

const CancelRouter = function () {
    const [data, setData] = useState<any>([]);
    const [pages, setPages] = useState<any>(1);
    const [loading, setLoading] = useState<any>(false);
    const [current, setCurrent] = useState(1);


    const loadMoreData = function ({ intRefreshing, pages: tmpPages }) {

        if (tmpPages == 1) {
            return getOrderList(intRefreshing);
        };

        console.log('pagesCounts', pages);

        if (current > pages) {
            return intRefreshing && intRefreshing();
        };

        const baseData = {
            current: tmpPages,
            size: 10,
            payStatus: 2,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                const newData = res.data.items;
                setPages(res.data.pages)
                setData((prevData) => [...prevData, ...newData]);
                setCurrent(current + 1);
                intRefreshing && intRefreshing();
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    useEffect(() => {
        getOrderList();
    }, [])

    const getOrderList = function (intRefreshing?: any) {
        const baseData = {
            current: 1,
            size: 10,
            payStatus: 2,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                setPages(res.data.pages)
                setData(res.data.items)
                intRefreshing && intRefreshing();
            })
            .catch((err) => {
                intRefreshing && intRefreshing();
            })
    };

    return (
        <View style={{ height: "100%"}}>
            {/*<FlatList*/}
            {/*    data={data}*/}
            {/*    renderItem={(item) => <OrderList data={item} /> }*/}
            {/*/>*/}

            <ProFlatList
                data={data}
                renderItem={(item, index) => <OrderList data={item} key={`${index}AllRouter`} /> }
                pages={pages}
                requestData={loadMoreData}
                loading={loading}
                setLoading={setLoading}
            />
        </View>
    )
};

const RefundRouter = function () {
    const [data, setData] = useState<any>([]);
    const [pages, setPages] = useState<any>(1);
    const [loading, setLoading] = useState<any>(false);
    const [current, setCurrent] = useState(1);


    const loadMoreData = function ({ intRefreshing, pages: tmpPages }) {

        if (tmpPages == 1) {
            return getOrderList(intRefreshing);
        };

        console.log('pagesCounts', pages);

        if (current > pages) {
            return intRefreshing && intRefreshing();
        };

        const baseData = {
            current: tmpPages,
            size: 10,
            payStatus: 4,
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                const newData = res.data.items;
                setPages(res.data.pages)
                setData((prevData) => [...prevData, ...newData]);
                setCurrent(current + 1);
                intRefreshing && intRefreshing();
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    useEffect(() => {
        getOrderList();
    }, [])

    const getOrderList = function (intRefreshing?: any) {
        const baseData = {
            current: 1,
            size: 10,
            payStatus: 4
        };
        getOrderListByRequest(baseData)
            .then((res) => {
                setPages(res.data.pages)
                setData(res.data.items)
                intRefreshing && intRefreshing();
            })
            .catch((err) => {
                intRefreshing && intRefreshing();
            })
    };

    return (
        <View style={{ height: "100%"}}>
            {/*<FlatList*/}
            {/*    data={data}*/}
            {/*    renderItem={(item) => <OrderList data={item} /> }*/}
            {/*/>*/}

            <ProFlatList
                data={data}
                renderItem={(item, index) => <OrderList data={item} key={`${index}AllRouter`} /> }
                pages={pages}
                requestData={loadMoreData}
                loading={loading}
                setLoading={setLoading}
            />
        </View>
    )
};


// 自定义的 TabBar 组件
const CustomTabBar = ({ navigationState, position, setIndex }) => {
    // 创建指示器的动态宽度和位置
    const inputRange = navigationState.routes.map((_, i) => i);
    const layoutWith = scaleSize(375);
    const translateX = position.interpolate({
        inputRange,
        outputRange: inputRange.map(i => i * layoutWith / 5 + ((layoutWith / 5)) / 5 + (10)),
        // outputRange: [48, 162], // 这里的值需要根据实际情况计算
    });


    return (
        <View style={styles.tabHeader}>
            <View style={styles.tabBar}>
                {navigationState.routes.map((route, i) => (
                    <TouchableOpacity
                        key={route.key}
                        onPress={() => setIndex(i)}
                        style={styles.tabItem}>
                        <Text style={{ color: navigationState.index === i ? '#EC6138' : 'black' }}>
                            {route.title}
                        </Text>
                    </TouchableOpacity>
                ))}
                {/* 自定义指示器 */}
                <Animated.View
                    style={[
                        styles.indicator,
                        { transform: [{ translateX }] },
                        { width: scaleSize(26) } // 指示器的宽度
                    ]}
                />
            </View>
        </View>
    );
};


export default function OrderScreen() {

    const layout = useWindowDimensions();

    const [index, setIndex] = React.useState(0);
    const [routes] = React.useState([
        { key: 'all', title: '全部' },
        { key: 'unpaid', title: '待支付' },
        { key: 'paid', title: '已支付' },
        { key: 'cancel', title: '已取消' },
        { key: 'refund', title: '已退款' },
    ]);

    const renderScene = SceneMap({
        all: AllRouter,
        unpaid: UnpaidRouter,
        paid: PaidRouter,
        cancel: CancelRouter,
        refund: RefundRouter,
    });

    const router = useRouter();


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '我的订单', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#FFF', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <TabView
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                initialLayout={{ width: layout.width }}
                renderTabBar={(props) => <CustomTabBar {...props} setIndex={setIndex} />} // 使用自定义的 TabBar
            />
        </View>

    );
}

const styles = StyleSheet.create({
    tabBar: {
        flexDirection: 'row',
        backgroundColor: 'white',
        position: 'relative', // 需要相对定位来放置指示器
        width:scaleSize(375),
        margin: "auto",
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 9,
        fontSize: 14,
        color: "#2A2B30"
    },
    indicator: {
        position: 'absolute',
        height: 3,
        backgroundColor: '#EC6138',
        bottom: 0,
        borderRadius: 5,
    },
    tabHeader: {
        // backgroundColor: "#fff",
        // borderBottomWidth: 1,
        // borderBottomColor: "#F1F2F5"
    },
    orderItemContainer: {
        marginTop: 10,
        marginLeft: 12,
        marginRight: 12,
        height: scaleSize(122),
        backgroundColor: "#fff",
        padding: 12,
        borderRadius: 8,
    },
    orderBody: {
        flexDirection: "row",
        borderBottomWidth: 1,
        borderBottomColor: "#F1F2F5",
        paddingBottom: 10,
    },
    orderContent: {
        marginLeft: 10,
    },
    orderBanner: {
        width: scaleSize(50),
        height: scaleSize(50),
        backgroundColor: "red",
        borderRadius: 4,
    },
    orderTitle: {
        width: 210,
        fontSize: 14,
        color: "#2A2B30",
    },
    orderMoney: {
        color: "#ED2A20",
        fontSize: 16,
    },
    orderFooter: {
        flexDirection: "row",
        justifyContent: "flex-end",
        alignItems: "center",
        marginTop: 12,
    },
    canncelOrder: {
        width: 72,
        height: 24,
        borderRadius: 12,
        borderWidth: 1,
        borderColor: "#C0C3CE",
        borderStyle: "solid",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    canncelOrderText: {
        fontSize: 12,
        color: "#2A2B30"
    },
    OrderbtnTwo: {
        width: 72,
        height: 24,
        borderRadius: 12,
        backgroundColor: "#EC6138",
        borderStyle: "solid",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginLeft: 12,
    },
    OrderbtnTwoText: {
        color: "#fff",
        fontSize: 12,
    },
});
